package com.michael.adapter.protocol;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class HttpQueryProtocol {

    private static final ThreadLocal<Map<String, String>> PARAM = new ThreadLocal<>();

    public static String getParam(String key) {
        Map<String, String> map = PARAM.get();
        if (map == null) {
            init();
        } else {
            return map.get(key);
        }
        map = PARAM.get();
        if (map == null) {
            return null;
        }
        return map.get(key);
    }

    public static Map<String, String> getParamMap() {
        Map<String, String> map = PARAM.get();
        if (map == null) {
            init();
        }
        return PARAM.get();
    }

    public static void init() {
        if (PARAM.get() == null) {
            buildParam();
        } else {
            PARAM.set(new HashMap<>());
            buildParam();
        }
    }

    public static void init(Map<String, String> map) {
        PARAM.set(map);
    }

    public static void remove() {
        PARAM.remove();
    }

    private static void buildParam() {
        Map<String, String> map = new HashMap<>();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 非web请求进来无 requestAttributes对象
        if (null != requestAttributes) {
            HttpServletRequest request =
                    ((ServletRequestAttributes) requestAttributes).getRequest();
            Enumeration<String> names = request.getParameterNames();
            while (names.hasMoreElements()) {
                String key = names.nextElement();
                String value = request.getParameter(key);
                map.put(key, value);
            }
        }
        PARAM.set(map);
    }


    public static void put(String key, String value) {
        if (PARAM.get() == null) {
            buildParam();
        }
        PARAM.get().put(key, value);
    }
}
